from mootdx.quotes import Quotes

"""
实时行情客户端
"""
class RealTimeQuotes:
    _instance = None
    _quotes_instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, init_quotes=True, **kwargs):
        # 注意：这里我们只在第一次创建实例时初始化Quotes
        if self._quotes_instance is None and init_quotes:
            self._quotes_instance = Quotes.factory(market='std', multithread=True, heartbeat=True, bestip=True,
                                                   timeout=15)


    def bars(self, symbol, frequency, start , offset ,adjust):
        # 代理调用Quotes实例的方法
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self._quotes_instance.bars(symbol=symbol, frequency=frequency,start = start, offset=offset ,adjust =adjust)

    def minute(self, symbol):
        # 代理调用Quotes实例的方法
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self._quotes_instance.minute(symbol=symbol)

    #查询历史分时行情
    def minutes(self, symbol, date=''):
        # 代理调用Quotes实例的方法
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self._quotes_instance.minutes(symbol=symbol,date=date)


    def quotes(self, symbol):
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self._quotes_instance.quotes(symbol=symbol)

    def ohlc(self, symbol, begin, end, adjust):
        if self._quotes_instance is None:
            raise RuntimeError("Quotes instance is not initialized. Call __init__ with init_quotes=True first.")
        return self._quotes_instance.ohlc(symbol=symbol ,begin=begin ,end=end ,adjust=adjust )


    # 提供一个可选的方法来重新初始化Quotes实例（如果需要的话）
    def reinit_quotes(self, **kwargs):
        self._quotes_instance = Quotes.factory(**kwargs)

    # 使用示例


if __name__ == '__main__':
    client = RealTimeQuotes()  # 默认会初始化Quotes实例
    #data = client.bars(symbol='300168', frequency=9, offset=1,start = 3038,adjust='' )
    #data = client.ohlc(symbol='300168', begin="2011-01-25", end="2024-7-11", adjust='qfq')
    data = client.ohlc(symbol='123232', begin="2011-01-25", end="2024-7-11", adjust='')
    #data = client.quotes(symbol='600036')
    print("数据：")
    print(data.to_string(header=True, sparsify=False))

    # 如果需要，可以在后续重新初始化Quotes实例
    # client.reinit_quotes(market='std', multithread=True, heartbeat=True, bestip=True, timeout=15)

